﻿package com.main
{
	import com.application.ApplicationDefault;
	
	import com.notifications.XmlEvent;
	
	import com.tools.*;
	
	import com.conf.GalleryConf;
	
	import flash.display.*;
	
	import flash.events.Event;
	
	public class DynamicGallery extends ApplicationDefault
	{
		private var xmlLoader : XmlLoader;
		
		private var _imagesContainer : Sprite;
		
		private var _imageLoading : Number;
		
		function DynamicGallery()
		{
			xmlLoader = new XmlLoader( "assets/gallery_infos.xml" );
			xmlLoader.addEventListener( XmlEvent.XML_LOADED, afficheXml, false );
			xmlLoader.addEventListener( XmlEvent.XML_FAILED, echecXml, false );
		}
		
		private function afficheXml( pEvt : XmlEvent ) : void
		{
			//trace( pEvt.target.data );
			var infos : Array = XmlParser.parseXml( pEvt.dataXml );
			
			if ( infos.length > 0 )
			{
				_imageLoading = 0;
				_imagesContainer = new Sprite( );
				createGallery( infos );
			}
		}
		
		private function echecXml( pEvt : XmlEvent ) : void
		{
			trace( pEvt.type );
		}
		
		private function createGallery( pArr : Array ) : void
		{
			var lng : uint = pArr.length;
			
			for ( var i : uint = 0 ; i < lng ; i++ )
			{
				var image : ImageLoader = new ImageLoader( pArr[ i ] );
				image.x = ( ( GalleryConf.IMAGE_MAX_WIDTH / GalleryConf.THUMB_RATIO ) + GalleryConf.IMAGE_SPACE_WIDTH ) * i;
				image.y = 0;
				_imageLoading ++;
				image.addEventListener( Event.COMPLETE, addToDisplay );
			}
		}
		
		private function addToDisplay( pEvt : Event ) : void
		{
			pEvt.currentTarget.removeEventListener( Event.COMPLETE, addToDisplay );
			_imagesContainer.addChild( pEvt.currentTarget as DisplayObject );
			
			_imageLoading --;
			trace( "image loading loaded :: " + _imageLoading );
			
			if ( _imageLoading == 0 )
			{
				_imagesContainer.x = ( ApplicationDefault.GLOBAL_STAGE.stageWidth - _imagesContainer.width ) / 2;
				addChild( _imagesContainer );
			}
		}
	}
}